package com.swak.template;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import freemarker.template.DefaultObjectWrapper;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.Version;

/**
 * 支持自定义的类型转换
 * 
 * @author 618lf
 */
public class FreeMarkerObjectWrapper extends DefaultObjectWrapper {

	public FreeMarkerObjectWrapper(Version incompatibleImprovements) {
		super(incompatibleImprovements);
	}

	@Override
	protected TemplateModel handleUnknownType(Object obj) throws TemplateModelException {
		if (obj instanceof LocalDateTime) {
			Timestamp timestamp = Timestamp.valueOf((LocalDateTime) obj);
			return new SimpleDate(timestamp);
		}
		if (obj instanceof LocalDate) {
			Date date = Date.valueOf((LocalDate) obj);
			return new SimpleDate(date);
		}
		if (obj instanceof LocalTime) {
			Time time = Time.valueOf((LocalTime) obj);
			return new SimpleDate(time);
		}
		return super.handleUnknownType(obj);
	}
}
